﻿/*
 ***************************************************************************
 * Microsoft Visual C# .NET
 * 名称：       App_Input_HappyPlanUpdForm
 * 类型：       控制层
 * 功能说明：   快乐管家-活动计划登记页面
 * 作者：       章 昕
 * 创建日期：   2007/11/05
 * 修改日期     修改者      修改内容
 * 
 * 
 * ---
 ***************************************************************************
*/
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Shpm.System.Validator;
using Shpm.System.Web.Control;
using log4net;
using Shpm.App.Input.Bean;
using Shpm.App.Input.Dao;
using Shpm.App.Commons.Db.Beans.Master;
using Shpm.System;
using Shpm.App.Commons.Utils;
using System.Text.RegularExpressions;
using Shpm.App.Master.Dao;
using Shpm.App.Master.Bean;

public partial class App_Input_HappyPlanUpdForm : System.Web.UI.Page
{
    // log
    protected static ILog log = LogManager.GetLogger(typeof(App_Input_HappyPlanUpdForm));

    protected string docContentHtml = string.Empty;


    // page load
    protected void Page_Load(object sender, EventArgs e)
    {        
        //txtActMainPsn.Attributes.Add("onchange", "showEmployeeName(this.id,'" + txtActMainPsnName.ClientID + "');");
        txtActMainPsn.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtActMainPsnName.ClientID + "');");
      //  txtActMainPsnName.Attributes.Add("onfocus", "document.getElementById('" + txtActMainPsn.ClientID + "').focus();");

        txtActCoPsn1.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtActCoPsn1Name.ClientID + "');");
      //  txtActCoPsn1Name.Attributes.Add("onfocus", "document.getElementById('" + txtActCoPsn1.ClientID + "').focus();");
        txtActCoPsn2.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtActCoPsn2Name.ClientID + "');");
      //  txtActCoPsn2Name.Attributes.Add("onfocus", "document.getElementById('" + txtActCoPsn2.ClientID + "').focus();");
        txtActCoPsn3.Attributes.Add("onblur", "showEmployeeName(this.id,'" + txtActCoPsn3Name.ClientID + "');");
      //  txtActCoPsn3Name.Attributes.Add("onfocus", "document.getElementById('" + txtActCoPsn3.ClientID + "').focus();");

        if (!Page.IsPostBack)
        {
            // 保存接收的参数
            ViewState["InpActName"] = Convert.ToString(Context.Items["InpActName"]);
            ViewState["InpActType"] = Convert.ToString(Context.Items["InpActType"]);
            ViewState["InpActStat1"] = Convert.ToString(Context.Items["InpActStat1"]);
            ViewState["InpActStat2"] = Convert.ToString(Context.Items["InpActStat2"]);
            ViewState["InpBeginDate"] = Convert.ToString(Context.Items["InpBeginDate"]);
            ViewState["InpEndDate"] = Convert.ToString(Context.Items["InpEndDate"]);

            ViewState["HidActName"] = Convert.ToString(Context.Items["HidActName"]);
            ViewState["HidActType"] = Convert.ToString(Context.Items["HidActType"]);
            ViewState["HidActStat1"] = Convert.ToString(Context.Items["HidActStat1"]);
            ViewState["HidActStat2"] = Convert.ToString(Context.Items["HidActStat2"]);
            ViewState["HidBeginDate"] = Convert.ToString(Context.Items["HidBeginDate"]);
            ViewState["HidEndDate"] = Convert.ToString(Context.Items["HidEndDate"]);
            ViewState["HidCommand"] = Convert.ToString(Context.Items["HidCommand"]);

            if (Context.Items.Contains("HidPageIndex"))
            {
                ViewState["HidPageIndex"] = Context.Items["HidPageIndex"];
            }

            // init page
            ViewState["MODE"] = "";
            if (Context.Items.Contains("MODE"))
            {
                ViewState["MODE"] = Context.Items["MODE"];
            }

            // 活动编号
            ViewState["ACTION_ID"] = Convert.ToString(Context.Items["ACTION_ID"]);

            // 初始化控件
            initPageControls();

            // get data
            bindSelectData(Convert.ToString(ViewState["ACTION_ID"]));

        }
        else
        {
            string htmlDoc = Convert.ToString(Request.Form["FCKeditor1"]);
            if (htmlDoc == null) htmlDoc = "";
            htmlDoc = Regex.Replace(htmlDoc, "\\n|\\r|\\t|\\v", ""); //^\s*|\s*$
            //this.ViewState["HTML_DOC"] = htmlDoc;
            this.docContentHtml = Regex.Replace(htmlDoc, "'", "\\'");
        }
    }

    // 保存按钮
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            // do validate check
            // page 
            ComValidateChecker vd = new ComValidateChecker();
            vd.CheckItems.Add(new CheckRequired(txtActName.Text, new ComMessage("E0094", "活动名称")));
            vd.CheckItems.Add(new CheckRequired(lstActType.Text, new ComMessage("E0094", "活动分类")));
            vd.CheckItems.Add(new CheckRequired(txtActDate.Text, new ComMessage("E0094", "活动日期")));
            vd.CheckItems.Add(new CheckRequired(txtActAddress.Text, new ComMessage("E0094", "活动地点")));
            vd.CheckItems.Add(new CheckRequired(txtActMainPsn.Text, new ComMessage("E0094", "责任人")));

            vd.CheckItems.Add(new CheckLong(txtActCount.Text, new ComMessage("E0322", "预计人数")));            
            vd.CheckItems.Add(new CheckDate(txtActDate.Text, "yyyy/MM/dd", new ComMessage("E0037", "活动日期")));
            vd.CheckItems.Add(new CheckDateRange(DateUtils.convertToString(DateTime.Now), txtActDate.Text, "yyyy/MM/dd", new ComMessage("E0329", new string[] { "当前日期", "活动日期" })));
            vd.CheckItems.Add(new CheckDouble(txtFeePropagandize.Text, 7, 2, new ComMessage("E0064", new string[] { "宣传费用", "7", "2" })));
            vd.CheckItems.Add(new CheckDouble(txtFeeManpower.Text, 7, 2, new ComMessage("E0064", new string[] { "人工费用", "7", "2" })));
            vd.CheckItems.Add(new CheckDouble(txtFeeMaterial.Text, 7, 2, new ComMessage("E0064", new string[] { "材料费用", "7", "2" })));
            vd.CheckItems.Add(new CheckDouble(txtFeeTraffic.Text, 7, 2, new ComMessage("E0064", new string[] { "交通费用", "7", "2" })));
            vd.CheckItems.Add(new CheckDouble(txtFeeOther.Text, 7, 2, new ComMessage("E0064", new string[] { "其他费用", "7", "2" })));
            vd.CheckItems.Add(new CheckDouble(txtFeeTotal.Text, 7, 2, new ComMessage("E0064", new string[] { "合计费用", "8", "2" })));
                        
            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // person exist
            if (!checkExistPerson(txtActMainPsn.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "责任人");
                return;
            }

            if (!string.IsNullOrEmpty(txtActCoPsn1.Text)
                && !checkExistPerson(txtActCoPsn1.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "协助人1");
                return;
            }
            if (!string.IsNullOrEmpty(txtActCoPsn2.Text)
                && !checkExistPerson(txtActCoPsn2.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "协助人2");
                return;
            } 
            if (!string.IsNullOrEmpty(txtActCoPsn3.Text)
                 && !checkExistPerson(txtActCoPsn3.Text))
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "协助人3");
                return;
            }

            // 权限check 是否允许更新
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["ACTION_ID"]))
                && !checkUpdateAuthority(Convert.ToString(ViewState["ACTION_ID"])))
            { return; }
                        
            // insert update
            Button btnClick = (Button)sender;
            ViewState["ACTION_ID"] = insertUpdate(btnClick.CommandName);
            bindSelectData(Convert.ToString(ViewState["ACTION_ID"]));            
            
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 删除按钮
    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            // 权限check 是否允许更新
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["ACTION_ID"]))
                && !checkUpdateAuthority(Convert.ToString(ViewState["ACTION_ID"])))
            { return; }

            HappyPlanDao dao = new HappyPlanDao();
            HappyPlanBean bean = new HappyPlanBean();
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["ACTION_ID"])))
            {
                bean.ActionId = Convert.ToInt32(ViewState["ACTION_ID"]);
                bean = dao.FindHappyPlan(bean);
                if (bean == null)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "活动计划");
                    return;
                }
                int delCnt = dao.Delete(bean);
                // clear form
                bindSelectData("");
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0003").ToString();
            }
        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }
    }

    // 审核按钮
    protected void btnAud_Click(object sender, EventArgs e)
    {

        try
        {
            // 领导审批区分
            int audLev = getJobLevel();
           
            // page check
            ComValidateChecker vd = new ComValidateChecker();
                          
            if (audLev > 1)
            {
                vd.CheckItems.Add(new CheckRequired(lstAud2.SelectedValue, new ComMessage("E0094", "公寓主任意见（选择）")));
            }
            else if (audLev > 0)
            {
                vd.CheckItems.Add(new CheckRequired(lstAud1.SelectedValue, new ComMessage("E0094", "部门经理意见（选择）")));
            }
            if (!vd.DoValidator())
            {
                ((Design_MasterPage)this.Master).InfoMessage = vd.ErrorMessage;
                return;
            }

            // 权限check 是否允许审批
            if (!checkAuditingAuthority(Convert.ToString(ViewState["ACTION_ID"])))
            { return; }

            // auditing update
            HappyPlanDao dao = new HappyPlanDao();
            HappyPlanBean bean = new HappyPlanBean();
            if (!string.IsNullOrEmpty(Convert.ToString(ViewState["ACTION_ID"])))
            {
                SysUserManager manager = new SysUserManager(Context);
                SysUserBean sysUserBean = manager.getSysUserBean();
                MstSysUserBean mstSysUserBean =
                    sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
                MstEmployeeBean mstEmpBean =
                    sysUserBean == null ? null : sysUserBean.getEmployeeBean();
                string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
                string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;

                bean.ActionId = Convert.ToInt32(ViewState["ACTION_ID"]);
                bean = dao.FindHappyPlan(bean);
                if (bean == null)
                {
                    ((Design_MasterPage)this.Master).InfoMessage =
                        HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "活动计划");
                    return;
                }
                bean.UserId = loginId;
                
                bean.AuditingFlg = false;                                
                if (audLev > 1)
                {   
                    // 公寓主任
                    bean.ManagerAdvice = lstAud2.SelectedValue;
                    bean.ManagerMemo = txtAudMemo2.Text;
                    if (!"0".Equals(bean.DepartmentAdvice))
                    { bean.AuditingFlg = true; }
                }
                else if (audLev > 0)
                {
                    // 部门经理
                    bean.DepartmentAdvice = lstAud1.SelectedValue;
                    bean.DepartmentMemo = txtAudMemo1.Text;
                    if (!"0".Equals(bean.ManagerAdvice))
                    { bean.AuditingFlg = true; }
                }

                dao.Update(bean);

                bindSelectData(Convert.ToString(bean.ActionId));
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0037").ToString().Replace("{0}","审批");
              

                // send message to work employee
                MessageBean beanMsg = new MessageBean();
                beanMsg.Subject = "审批活动计划结果--" + DateTime.Now.ToString();
                if (audLev > 1)
                { beanMsg.Message = string.Format("公寓主任\n审批结果：{0}\n审批意见：{1}", lstAud2.Items[lstAud2.SelectedIndex].Text, bean.ManagerMemo); }
                else if (audLev > 0)
                { beanMsg.Message = string.Format("部门经理\n审批结果：{0}\n审批意见：{1}", lstAud1.Items[lstAud1.SelectedIndex].Text, bean.DepartmentMemo); }
                beanMsg.MessageType = 3;
                beanMsg.SendDate = DateTime.Now;
                beanMsg.ReplyFlag = false;
                beanMsg.ReaderHistoryFlag = false;
                beanMsg.ImportantFlag = false;
                beanMsg.EmployeeId = emplyId;
                beanMsg.UserId = loginId;
                string toEmployeeId = bean.EmployeeId;
                CommonSendMessageUtils sendMsg = new CommonSendMessageUtils(beanMsg, toEmployeeId);
                sendMsg.SendMessage();   
            }

        }
        catch (Exception ex)
        {
            log.Fatal(ex.StackTrace);
            log.Fatal(ex.Message);
            throw ex;
        }

    }

    // 返回按钮
    protected void btnBack_Click(object sender, EventArgs e)
    {
        string url = "~/App/Input/HappyPlanSrhForm.aspx";

        // 回传接收的参数       
        Context.Items["InpActName"] = ViewState["InpActName"];
        Context.Items["InpActType"] = ViewState["InpActType"];
        Context.Items["InpActStat1"] = ViewState["InpActStat1"];
        Context.Items["InpActStat2"] = ViewState["InpActStat2"];
        Context.Items["InpBeginDate"] = ViewState["InpBeginDate"];
        Context.Items["InpEndDate"] = ViewState["InpEndDate"];
        
        Context.Items["HidActName"] = ViewState["HidActName"];
        Context.Items["HidActType"] = ViewState["HidActType"];
        Context.Items["HidActStat1"] = ViewState["HidActStat1"];
        Context.Items["HidActStat2"] = ViewState["HidActStat2"];
        Context.Items["HidBeginDate"] = ViewState["HidBeginDate"];
        Context.Items["HidEndDate"] = ViewState["HidEndDate"];
        Context.Items["HidCommand"] = ViewState["HidCommand"];
        Context.Items["HidPageIndex"] = ViewState["HidPageIndex"];

        ControllerUtils.Transfer(Context, url, true);    
    }

    // check auditing person authority(审核人权限check)
    private Boolean checkAuditingAuthority(string actionId)
    {
        // get employee info
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;


        HappyPlanDao dao = new HappyPlanDao();
        HappyPlanBean bean = new HappyPlanBean();
        bean.ActionId = Convert.ToInt32(actionId);
        bean = dao.FindHappyPlan(bean);
        if (bean == null            
            || getJobLevel() < 1)
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return false;
        }

        // 是否已经审批通过
        if (bean.AuditingFlg != null && bean.AuditingFlg.Value)
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0029").ToString().Replace("{0}", "已经审批");
            return false;
        }

        // 是否已经提交
        if (bean.CommitFlg == null 
            || (bean.CommitFlg != null && !bean.CommitFlg.Value))
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0036").ToString().Replace("{0}", "还未提交");
            return false;
        }

        return true;
    }

    // check person exist
    private Boolean checkExistPerson(string empId)
    {
        HappyPlanDao dao = new HappyPlanDao();
        PersonEmployeeBean beanME = new PersonEmployeeBean();
        beanME.EmployeeId = empId;
        beanME = dao.GetEmployee(beanME);
        if (beanME == null)
        { return false; }

        return true;
    }

    // check authority for update（更新人 登记人 是否同一人） 
    private Boolean checkUpdateAuthority(string actionId)
    {
        if (string.IsNullOrEmpty(actionId))
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return false;
        }

        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;

        HappyPlanDao dao = new HappyPlanDao();
        HappyPlanBean bean = new HappyPlanBean();
        bean.ActionId = Convert.ToInt32(actionId);
        bean = dao.FindHappyPlan(bean);
        if (bean == null
            || string.IsNullOrEmpty(bean.EmployeeId)
            || !emplyId.Equals(bean.EmployeeId))
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0901").ToString();
            return false; 
        }        

        // 是否已经审批通过
        if (!"0".Equals(bean.DepartmentAdvice)
            || !"0".Equals(bean.ManagerAdvice))
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0029").ToString().Replace("{0}", "上级已经审批");
            return false; 
        }
        
        // 是否已经提交
        if (bean.CommitFlg != null && bean.CommitFlg.Value)
        {
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0036").ToString().Replace("{0}", "已经提交");
            return false;
        }

        return true;
    }

    // 插入 更新 数据 
    private string insertUpdate(string buttonCommond)
    {
        string retKey = string.Empty;

        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;

        // get date from page
        HappyPlanDao dao = new HappyPlanDao();
        HappyPlanBean bean = new HappyPlanBean();
        bean.ActionName = txtActName.Text;
        bean.ActionType = lstActType.SelectedValue;
        if (!string.IsNullOrEmpty(txtActDate.Text))
        {bean.BespokeDate = DateUtils.convertToDate(txtActDate.Text);}               
        bean.BespokeDateText = txtActDateMemo.Text;
        bean.ActionAddress = txtActAddress.Text;
        bean.ActionObject =  txtActObject.Text;
        if (!string.IsNullOrEmpty(txtActCount.Text))
        { bean.ActionCount = Convert.ToInt32(txtActCount.Text); }
        bean.ResponsibilityId = txtActMainPsn.Text;
        if (!string.IsNullOrEmpty(txtActCoPsn1.Text))
        { bean.CoadjutantId = txtActCoPsn1.Text; }
        if (!string.IsNullOrEmpty(txtActCoPsn2.Text))
        { bean.Coadjutant2Id = txtActCoPsn2.Text; }
        if (!string.IsNullOrEmpty(txtActCoPsn3.Text))
        { bean.Coadjutant3Id = txtActCoPsn3.Text; }

        // fee
        if (!string.IsNullOrEmpty(txtFeePropagandize.Text))
        { bean.FeePropagandize = Convert.ToDecimal(txtFeePropagandize.Text); }
        if (!string.IsNullOrEmpty(txtFeeManpower.Text))
        { bean.FeeManpower = Convert.ToDecimal(txtFeeManpower.Text); }
        if (!string.IsNullOrEmpty(txtFeeMaterial.Text))
        { bean.FeeMaterial = Convert.ToDecimal(txtFeeMaterial.Text); }
        if (!string.IsNullOrEmpty(txtFeeTraffic.Text))
        { bean.FeeTraffic = Convert.ToDecimal(txtFeeTraffic.Text); }
        if (!string.IsNullOrEmpty(txtFeeOther.Text))
        { bean.FeeOther = Convert.ToDecimal(txtFeeOther.Text); }

        // content
        // original html text
        string htmlDoc = Request.Form["FCKeditor1"];
        htmlDoc = Regex.Replace(htmlDoc, "\\n|\\r|\\t|\\v", ""); //^\s*|\s*$
        string tmpKeyword = htmlDoc;
        bean.ActionContent = Regex.Replace(htmlDoc, "'", "\\'");
        // key word html text
        //string htmlKeyWord = Regex.Replace(tmpKeyword, "<[^><]*>", "");
        //htmlKeyWord = Server.HtmlDecode(htmlKeyWord);
        //beanDC.ContentKeyword = htmlKeyWord;
        //bean.ActionContent = txtMemo1.Text;
        bean.ActionDocument = txtMemo2.Text;

        bean.UserId = loginId;
        if (string.IsNullOrEmpty(Convert.ToString(ViewState["ACTION_ID"])))
        {
            // new plan insert
            bean.EmployeeId = emplyId;
            bean.DepartmentAdvice = "0";
            bean.ManagerAdvice = "0";
            bean.CommitFlg = false;
            // 已提交
            if ("COMPLETE".Equals(buttonCommond))
            { bean.CommitFlg = true; }            
            bean.AuditingFlg = false;
            bean.CompleteFlg = false;
            bean = dao.Insert(bean);
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0001").ToString();
        }
        else
        {
            // edit plan update
            HappyPlanBean beanOld = new HappyPlanBean();
            beanOld.ActionId = Convert.ToInt32(ViewState["ACTION_ID"]);
            beanOld = dao.FindHappyPlan(beanOld);
            if (beanOld == null)
            {
                ((Design_MasterPage)this.Master).InfoMessage =
                    HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "活动计划");
                return string.Empty;
            }
            bean.ActionId = beanOld.ActionId;
            bean.EmployeeId = beanOld.EmployeeId;
            bean.DepartmentAdvice = beanOld.DepartmentAdvice;
            bean.ManagerAdvice = beanOld.ManagerAdvice;
            bean.DepartmentMemo = beanOld.DepartmentMemo;
            bean.ManagerMemo = beanOld.ManagerMemo;
            bean.CommitFlg = beanOld.CommitFlg;
            // 已提交
            if ("COMPLETE".Equals(buttonCommond))
            { bean.CommitFlg = true; }            
            bean.AuditingFlg = beanOld.AuditingFlg;
            bean.CompleteFlg = beanOld.CompleteFlg;
            dao.Update(bean);
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "I0002").ToString();
        }        

        retKey = Convert.ToString(bean.ActionId);

        //发送消息
        if ("COMPLETE".Equals(buttonCommond))
        {
            MessageBean beanMsg = new MessageBean();
            beanMsg.Subject = "审批快乐活动--" + DateUtils.convertToString(DateTime.Now);
            beanMsg.Message = "快乐活动已做成，烦请领导审批！";

            beanMsg.MessageType = 3;
            beanMsg.SendDate = DateTime.Now;
            beanMsg.ReplyFlag = false;
            beanMsg.ReaderHistoryFlag = false;
            beanMsg.ImportantFlag = false;
            beanMsg.EmployeeId = emplyId;
            beanMsg.UserId = loginId;

            EmployeeDao employeeDao = new EmployeeDao();
            EmployeeBean employeeBean = new EmployeeBean();
            CommonSendMessageUtils sendMsg = null;
            //管家部经理
            employeeBean.DepartId = mstEmpBean.DepartId;
            employeeBean.GroupId = 152;
            IList list = employeeDao.FindEmployees(employeeBean);
            for (int i = 0; i < list.Count; i++)
            {
                sendMsg = new CommonSendMessageUtils(beanMsg, (list[i] as EmployeeBean).EmployeeId);
                sendMsg.SendMessage();
            }
            //公寓主任
            employeeBean.GroupId = 151;
            list = employeeDao.FindEmployees(employeeBean);
            for (int i = 0; i < list.Count;i++ )
            {
                sendMsg = new CommonSendMessageUtils(beanMsg, (list[i] as EmployeeBean).EmployeeId);
                sendMsg.SendMessage();   
            }
           
            
        }
        return retKey;
    }

    // bind data to controls
    private void bindSelectData(string actionId)
    {
        if ("EDIT".Equals(Convert.ToString(ViewState["MODE"])))
        {
            // edit mode 快乐管家 登记mode
            lstAud1.Enabled = false;
            lstAud2.Enabled = false;
            txtAudMemo1.Enabled = false;
            txtAudMemo2.Enabled = false;
            btnAud.Enabled = false;
            btnAud.Visible = false;
        }
        else if("AUDI".Equals(Convert.ToString(ViewState["MODE"])))
        {
            // auditing mode 领导 审核mode
            btnOk.Enabled = false;
            btnOk.Visible = false;
            btnSubmit.Enabled = false;
            btnSubmit.Visible = false;
            btnDel.Enabled = false;
            btnDel.Visible = false;
            txtActName.Enabled = false;
            lstActType.Enabled = false;
            txtActDate.Enabled = false;
            txtActDateMemo.Enabled = false;
            txtActAddress.Enabled = false;
            txtActObject.Enabled = false;
            txtActCount.Enabled = false;
            txtActMainPsn.Enabled = false;
            txtActMainPsnName.Enabled = false;
            txtActCoPsn1.Enabled = false;
            txtActCoPsn1Name.Enabled = false;
            txtActCoPsn2.Enabled = false;
            txtActCoPsn2Name.Enabled = false;
            txtActCoPsn3.Enabled = false;
            txtActCoPsn3Name.Enabled = false;
            // fee
            txtFeePropagandize.Enabled = false;
            txtFeeManpower.Enabled = false;
            txtFeeMaterial.Enabled = false;
            txtFeeTraffic.Enabled = false;
            txtFeeOther.Enabled = false;
            txtFeeTotal.Enabled = false;
            // content
            //txtMemo1.Enabled = false;
            txtMemo2.Enabled = false;

            // 领导审批权限区分
            lstAud1.Enabled = false;
            txtAudMemo1.Enabled = false;
            lstAud2.Enabled = false;
            txtAudMemo2.Enabled = false;
            int level = getJobLevel();
            if (level > 1)
            {
                lstAud2.Enabled = true;
                txtAudMemo2.Enabled = true;
            }
            else if (level > 0)
            {
                lstAud1.Enabled = true;
                txtAudMemo1.Enabled = true;
            }
        }

        if (string.IsNullOrEmpty(Convert.ToString(actionId)))
        {
            // 新建 活动计划
            ViewState["ACTION_ID"] = "";
            btnDel.Enabled = false;
            resetFormControls();
            return;
        }
        
        // 编辑 活动计划
        // 读取 活动计划数据
        HappyPlanDao dao = new HappyPlanDao();
        HappyPlanBean bean = new HappyPlanBean();
        bean.ActionId = Convert.ToInt32(actionId);
        bean = dao.FindHappyPlan(bean);
        if (bean == null)        
        {
            ViewState["ACTION_ID"] = "";
            btnDel.Enabled = false;
            resetFormControls();
            ((Design_MasterPage)this.Master).InfoMessage =
                HttpContext.GetGlobalResourceObject(Constants.GLOBAL_RESOURCE_NAME, "E0203").ToString().Replace("{0}", "活动计划");
            return;
        }
        //btnDel.Enabled = true;
        // set data to page
        lblActId.Text = Convert.ToString(bean.ActionId);
        txtActName.Text = bean.ActionName;
        lstActType.SelectedValue = bean.ActionType;
        if (bean.BespokeDate != null)
        { txtActDate.Text = DateUtils.convertToString(bean.BespokeDate.Value); }
        txtActDateMemo.Text = bean.BespokeDateText;
        txtActAddress.Text = bean.ActionAddress;
        txtActObject.Text = bean.ActionObject;
        if (bean.ActionCount != null)
        { txtActCount.Text = Convert.ToString(bean.ActionCount); }
        txtActMainPsn.Text = bean.ResponsibilityId;
        txtActCoPsn1.Text = bean.CoadjutantId;
        txtActCoPsn2.Text = bean.Coadjutant2Id;
        txtActCoPsn3.Text = bean.Coadjutant3Id;
        txtActMainPsnName.Text = bean.RespPesonName;
        txtActCoPsn1Name.Text = bean.CoPeson1Name;
        txtActCoPsn2Name.Text = bean.CoPeson2Name;
        txtActCoPsn3Name.Text = bean.CoPeson3Name;

        // fee
        if (bean.FeePropagandize != null)
        { txtFeePropagandize.Text = String.Format("{0:N}", bean.FeePropagandize); }
        if (bean.FeeManpower != null)
        { txtFeeManpower.Text = String.Format("{0:N}", bean.FeeManpower); }
        if (bean.FeeMaterial != null)
        { txtFeeMaterial.Text = String.Format("{0:N}", bean.FeeMaterial); }
        if (bean.FeeTraffic != null)
        { txtFeeTraffic.Text = String.Format("{0:N}", bean.FeeTraffic); }
        if (bean.FeeOther != null)
        { txtFeeOther.Text = String.Format("{0:N}", bean.FeeOther); }
        txtFeeTotal.Text = bean.Amount;

        // content
        this.docContentHtml = bean.ActionContent;
        //txtMemo1.Text = bean.ActionContent;
        txtMemo2.Text = bean.ActionDocument;
        
        // auditing
        if (lstAud1.Items.FindByValue(bean.DepartmentAdvice) != null)
        { lstAud1.SelectedValue = bean.DepartmentAdvice; }
        if (lstAud2.Items.FindByValue(bean.ManagerAdvice) != null)
        { lstAud2.SelectedValue = bean.ManagerAdvice; }
        txtAudMemo1.Text = bean.DepartmentMemo;
        txtAudMemo2.Text = bean.ManagerMemo;
        
        // 已提交状态
        if (bean.CommitFlg != null && bean.CommitFlg.Value)
        {
            btnOk.Enabled = false;
            btnSubmit.Enabled = false;
            btnDel.Enabled = false;
        }
        // 已审核状态
        if (bean.AuditingFlg != null && bean.AuditingFlg.Value)
        {
            btnAud.Enabled = false;
            btnOk.Enabled = false;
            btnSubmit.Enabled = false;
            btnDel.Enabled = false;
        }       
    }

    // 取得审批权限
    private int getJobLevel()
    {
        SysUserManager manager = new SysUserManager(Context);
        SysUserBean sysUserBean = manager.getSysUserBean();
        MstSysUserBean mstSysUserBean =
            sysUserBean == null ? null : sysUserBean.getMstSysUserBean();
        MstEmployeeBean mstEmpBean =
            sysUserBean == null ? null : sysUserBean.getEmployeeBean();
        string loginId = mstSysUserBean == null ? "" : mstSysUserBean.SysUserId;
        string emplyId = mstSysUserBean == null ? "" : mstSysUserBean.EmployeeId;
        PersonEmployeeBean beanEmp = new PersonEmployeeBean();
        HappyPlanDao dao = new HappyPlanDao();
        beanEmp.EmployeeId = emplyId;
        beanEmp = dao.GetEmployeeJob(beanEmp);
        if (beanEmp == null || string.IsNullOrEmpty(beanEmp.JobLimit))
        { return 0; }
        return Convert.ToInt32(beanEmp.JobLimit);
    }

    // reset controls to page
    private void resetFormControls()
    {
        lblActId.Text = string.Empty;
        txtActName.Text = string.Empty;
        if (lstActType.Items.Count > 0) lstActType.SelectedIndex = 0;
        txtActDate.Text = string.Empty;
        txtActDateMemo.Text = string.Empty;
        txtActAddress.Text = string.Empty;
        txtActObject.Text = string.Empty;
        txtActCount.Text = string.Empty;
        txtActMainPsn.Text = string.Empty;
        txtActMainPsnName.Text = string.Empty;
        txtActCoPsn1.Text = string.Empty;
        txtActCoPsn1Name.Text = string.Empty;
        txtActCoPsn2.Text = string.Empty;
        txtActCoPsn2Name.Text = string.Empty;
        txtActCoPsn3.Text = string.Empty;
        txtActCoPsn3Name.Text = string.Empty;

        // fee        
        txtFeePropagandize.Text = string.Empty;        
        txtFeeManpower.Text = string.Empty;        
        txtFeeMaterial.Text = string.Empty;        
        txtFeeTraffic.Text = string.Empty;
        txtFeeOther.Text = string.Empty;
        txtFeeTotal.Text = string.Empty;

        // content
        //txtMemo1.Text = string.Empty;
        txtMemo2.Text = string.Empty;

        // auditing
        if (lstAud1.Items.Count > 0) lstAud1.SelectedIndex = 0;
        if (lstAud2.Items.Count > 0) lstAud2.SelectedIndex = 0;
        txtAudMemo1.Text = string.Empty;
        txtAudMemo2.Text = string.Empty;
    }

    // bind common catalog data 
    private void initPageControls()
    {
        HappyPlanDao dao = new HappyPlanDao();
        CommonDictionaryBean beanComDict = new CommonDictionaryBean();
        IList lstCat = null;

        // 活动分类
        log.Fatal("\n ***** get 活动分类 catalog *****");
        beanComDict.Catalog = "T_ACTION_ADVICE.ADVICE_TYPE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstActType.Items.Clear();
        bindDataToListControl("lstActType", lstCat);

        // 审核状态
        log.Fatal("\n ***** get 审核状态 catalog *****");
        beanComDict.Catalog = "T_ACTION_ADVICE.DEPARTMENT_ADVICE";
        lstCat = dao.FindByCatalog(beanComDict);
        lstAud1.Items.Clear();
        lstAud2.Items.Clear();
        bindDataToListControl("lstAud1", lstCat);
        //if (lstAud1.Items.Count > 0) lstAud1.Items.RemoveAt(0);
        bindDataToListControl("lstAud2", lstCat);
        //if (lstAud2.Items.Count > 0) lstAud2.Items.RemoveAt(0);
    }

    // bind db data to selected controls
    private void bindDataToListControl(string ControlId, IList LstData)
    {
        if (LstData == null || LstData.Count == 0) return;

        foreach (CommonDictionaryBean bean in LstData)
        {
            if (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is DropDownList)
            {
                ((DropDownList)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
            else if ((this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is CheckBoxList)
                || (this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId) is RadioButtonList))
            {
                ((ListControl)this.Master.FindControl("ContentPlaceHolder1").FindControl(ControlId)).Items.Add(new ListItem(bean.Content, bean.DictNo.ToString()));
            }
        }
    }


}
